package ag.script.project.standard.screen;

import ag.script.project.standard.entity.AgAppConfig;
import ag.script.project.standard.core.ScreensDes;
import cn.hutool.core.util.StrUtil;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;

public class ParserScreens {
    private AgAppConfig config;

    public ParserScreens(AgAppConfig config) {
        this.config = config;
    }

    public List<ScreensDes> parse(String configJson) {
        this.config = new Gson().fromJson(configJson, AgAppConfig.class);
        return parse();
    }

    public ScreensDes parseSingle(String screen) {

        //如果书写格式是：1080*1920，替换成1080x1920
        String s_1 = StrUtil.replace(screen.trim().toLowerCase(), "*", "x");
        //如果书写格式是：1080x?，替换成1080x
        screen = StrUtil.replace(s_1, "?", "");


        ScreensDes des = new ScreensDes();
        des.setName(screen);
        //x1920
        if (StrUtil.startWith(screen, "x")) {
            des.setAllH(true);
            des.setHasAll(true);
            String height = StrUtil.removePrefix(screen, "x");
            des.setH(Integer.parseInt(height));
            des.setDes("支持高度为" + height + "的全部手机");
            return des;
        }

        //1080x
        if (StrUtil.endWith(screen, "x")) {
            des.setAllW(true);
            des.setHasAll(true);
            String width = StrUtil.removeSuffix(screen, "x");
            des.setW(Integer.parseInt(width));
            des.setDes("支持宽度为" + width + "的全部手机");
            return des;
        }

        //1080x1920
        List<String> split = StrUtil.split(screen, "x");
        des.setHasAll(false);
        des.setW(Integer.parseInt(split.get(0)));
        des.setH(Integer.parseInt(split.get(1)));
        des.setDes("只支持宽为" + des.getW() + "高为" + des.getH() + "的手机");
        return des;
    }

    public List<ScreensDes> parse() {

        List<String> screens = config.getScreens();
        if (screens == null || screens.isEmpty()) {
            return null;
        }
        List<ScreensDes> desList = new ArrayList<>();

        for (String screen : screens) {
            ScreensDes des = parseSingle(screen); //解析单个屏幕
            desList.add(des);
        }

        return desList;
    }

}
